var express = require('express')
var router = express.Router()
const models = require('../../models')
const {success, error} = require('../../utils/message')
const checkPermission = require('../../middlewares/check-permission');

// 分类列表
router.get('/', checkPermission(), async function (req, res, next) {
    let categories = await models.Category.findAll({
        order: [
            ['sort', 'ASC'],
            ['children', 'sort', 'ASC']
        ],
        where: {parentId: 0},
        include: [{
            model: models.Category,
            as: 'children'
        }]
    })
    success(res, '查询成功', {categories})
})

// 新增分类
router.post('/', checkPermission(), async function (req, res, next) {
    const name = req.body.name
    const sort = req.body.sort

    if (!name) {
        return error(res, '请填写名称')
    }

    if (!sort) {
        return error(res, '请填写排序')
    }

    if (!Number(sort)) {
        return error(res, '排序必须是数字')
    }

    const categoryName = await models.Category.findOne({where: {name: name}})
    if (categoryName) {
        return error(res, '分类名称已存在，请勿重复添加')
    }

    let category = await models.Category.create(req.body)
    success(res, '新增成功', {category})
});

// 查询单条分类
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const category = await models.Category.findByPk(id)
    if (!category) {
        return error(res, '当前分类不存在，无法修改')
    }

    success(res, '查询成功', {category})
})

// 修改分类
router.put('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const name = req.body.name
    const sort = req.body.sort

    if (!name) {
        return error(res, '请填写名称')
    }

    if (!sort) {
        return error(res, '请填写排序')
    }

    if (!Number(sort)) {
        return error(res, '排序必须是数字')
    }

    const category = await models.Category.findByPk(id)
    if (!category) {
        return error(res, '当前分类不存在，无法修改')
    }

    category.update(req.body)
    success(res, '修改成功', {category})
})

// 删除分类
router.delete('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const category = await models.Category.findOne({
        where: {id: id},
        include: [{
            model: models.Category,
            as: 'children',
        }],
    })

    if (category.children.length > 0) {
        return error(res, '当前分类有子分类，不能删除。请先将子分类删除后，再来操作！')
    }

    category.destroy()
    success(res, '删除成功')
})

// 修改排序
router.patch('/:id/change_sort', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const sort = req.body.sort

    if (!sort) {
        return error(res, '请填写排序')
    }

    if (!Number(sort)) {
        return error(res, '排序必须是数字')
    }

    const category = await models.Category.findByPk(id)

    category.update({sort: sort})
    success(res, '修改排序成功')
})

module.exports = router
